var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser')


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
        extended: false
    }))
    // parse application/json
app.use(bodyParser.json())


app.use(express.static('xueyuanguanli1'));


var Class = require("./class").Class;

//分页
app.get("/list_class", function(req, res) {
    var pageSize = parseInt(req.query["pageSize"]);
    var pageNo = parseInt(req.query["pageNo"]);
    var dbquery = Class.find({});
    dbquery.skip(pageSize * pageNo); //跳过多少条
    dbquery.limit(pageSize); //页数
    dbquery.find({}, function(err, list) {
        Class.count({}, function(arr, total) {
            if (err) {
                res.json({
                    status: 500,
                    message: "查询错误"
                });
            } else {
                res.json({
                    status: 200,
                    total: total,
                    pageSize: pageSize,
                    pageNo: pageNo,
                    list: list,
                })
            }
        })
    })
});
//删除
app.delete("/class", function(req, res) {
    var index = req.query["index"] //查询id
    console.log(index)
    var wherestr = {
        "_id": index
    }
    Class.remove(wherestr, function(err) {
        if (err) {
            res.json({
                code: -1,
                message: "删除失败"
            })
        } else {
            res.json({
                code: 1,
                message: "删除成功"
            })
        }
    })
});

//添加
app.post("/class2", function(req, res) {
    var data = req.body;
    var c1 = new Class(data);
    c1.save(function(err) {
        if (err) {
            res.json({
                code: -1,
                message: "添加失败"
            })
        } else {
            res.json({
                code: 1,
                message: "添加成功"
            })
        }

    });

});

//编辑
app.put("/class1", function(req, res) {
    var data = req.body;

    // console.log(data)
    var index = req.query["index"]
        // console.log(index);
    var wherestr = {
            "_id": index
        }
        // var updatestr = new Class(data)
        // delete updatestr._id

    var updatestr = data

    console.log(updatestr)
    Class.update(wherestr, updatestr, function(err) {
        if (err) {
            res.json({
                code: -1,
                message: "编辑失败"
            })
        } else {
            res.json({
                code: 1,
                message: "编辑成功"
            })
        }
    })

});



console.log("listen to ")
app.listen(8081);